/********************************************************/
/*	Author:		gong_libin			*/
/*	Date:		2017_11_01			*/
/*	File:		CmTrans.cpp			*/
/********************************************************/

#include "CmTrans.h"

char* CCmTrans::CmTransName()
{
	return m_szName;
}

CMLINK_S* CCmTrans::CmTransLink()
{
	return m_stLink;
}

UINT CCmTrans::CmTransGetOne()
{
	UINT uiTop = m_uiCur ++;

	m_CLock.CmLockLock();
	while (uiTop != (m_uiCur = (m_uiCur % CM_LNK_NUM))) {
		if (CM_LNK_IDLE == m_stLink[m_uiCur].m_cTag) {
			m_stLink[m_uiCur].m_cTag = CM_LNK_BUSY;
			break;
		}
		m_uiCur += 1;
	}
	m_CLock.CmLockUnlock();

	return uiTop == m_uiCur ? CM_LNK_NUM : m_uiCur;
}

void CCmTrans::CmTransPayOne(CMLINK_S* pstLink)
{
	m_CLock.CmLockLock();
	pstLink->m_cTag = CM_LNK_IDLE;
	m_CLock.CmLockUnlock();

	return;
}

void CCmTrans::CmTransTimeout(CMLINK_S* pstLink)
{
	m_CLock.CmLockLock();
	pstLink->m_CTcp.CmNetClose();
	pstLink->m_cTag = CM_LNK_ZERO;
	m_CLock.CmLockUnlock();

	return;
}

int CCmTrans::CmTransConnectAll(char* pszUrl)
{
	int iReturn = CM_SUCCESS;

	for (m_uiCur = 0; m_uiCur < CM_LNK_NUM; m_uiCur ++) {
		if (CM_SUCCESS != (iReturn = CmTransConnectOne(&m_stLink[m_uiCur], pszUrl))) {
			break;
		}
	}

	return iReturn;
}

void CCmTrans::CmTransCloseAll()
{
	for (m_uiCur = 0; m_uiCur < CM_LNK_NUM; m_uiCur ++) {
		CmTransCloseOne(&m_stLink[m_uiCur]);
	}

	return;
}

int CCmTrans::CmTransConnectOne(CMLINK_S* pstLink, char* pszUrl)
{
	int iReturn = CM_SUCCESS;
	char szUrl[CM_URL] = {'\0'};

	strcpy(szUrl, pszUrl);

	m_CLock.CmLockLock();
	if (CM_LNK_ZERO == pstLink->m_cTag) {
		if (CM_SUCCESS == (iReturn = pstLink->m_CTcp.CmTcpConnect(szUrl))) {
			pstLink->m_cTag = CM_LNK_IDLE;
		}
	}
	m_CLock.CmLockUnlock();

	return iReturn;
}

void CCmTrans::CmTransCloseOne(CMLINK_S* pstLink)
{
	m_CLock.CmLockLock();
	if (CM_LNK_ZERO != pstLink->m_cTag) {
		pstLink->m_CTcp.CmNetClose();
		pstLink->m_cTag = CM_LNK_ZERO;
	}
	m_CLock.CmLockUnlock();

	return;
}

void CCmTrans::CmTransMonitor(char* pszUrl)
{
	for (m_uiCur = 0; m_uiCur < CM_LNK_NUM; m_uiCur ++) {
		CmTransConnectOne(&m_stLink[m_uiCur], pszUrl);
	}

	return;
}

bool CCmTrans::CmTransNew(char* pszName)
{
	m_uiCur = 0;
	memcpy(m_szName, pszName, strlen(pszName));
	memset(&m_stLink, '\0', sizeof(CMLINK_S) * CM_LNK_NUM);

	return CM_SUCCESS == m_CLock.CmLockCreate() ? true : false;
}

void CCmTrans::CmTransDel()
{
	m_uiCur = 0;
	m_CLock.CmLockDelete();
	memset(m_szName,'\0', CM_BUFFER);
	memset(&m_stLink, '\0', sizeof(CMLINK_S) * CM_LNK_NUM);

	return;
}
